const { generateToken04 } = require('../utils/zegoServerAssistant');

class ZegoTokenService {
  constructor() {
    this.appId = parseInt(process.env.ZEGO_APP_ID, 10);
    this.serverSecret = process.env.ZEGO_SERVER_SECRET;

    if (!this.appId) {
      throw new Error('ZEGO_APP_ID 未配置');
    }
    if (!this.serverSecret || this.serverSecret.length !== 32) {
      throw new Error('ZEGO_SERVER_SECRET 未配置或长度不是 32 字节');
    }
  }

  /**
   * 生成 Zego Token
   * @param {Object} opts
   * @param {string} opts.userId - 用户 ID
   * @param {string} opts.roomId - 房间 ID
   * @param {number} [opts.expire=3600] - token 有效期，秒
   * @param {boolean} [opts.allowPublish=false] - 是否允许推流权限
   * @returns {string} token 字符串
   */
  createToken({ userId, roomId, expire = 3600, allowPublish = false }) {
    if (!userId) throw new Error('userId 不能为空');
    if (!roomId) throw new Error('roomId 不能为空');

    const payloadObject = {
      room_id: roomId,
      privilege: {
        1: 1, // loginRoom
        2: allowPublish ? 1 : 0 // publishStream
      },
      stream_id_list: null
    };

    const token = generateToken04(
      this.appId,
      userId,
      this.serverSecret,
      expire,
      JSON.stringify(payloadObject)
    );

    return token;
  }
}

module.exports = new ZegoTokenService(); 